package com.example.demo21;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewPager viewPager=findViewById(R.id.viewPager);
        LayoutInflater inflater=getLayoutInflater();
        View a1 = inflater.inflate(R.layout.a1,null);
        View a2 = inflater.inflate(R.layout.a2,null);
        View a3 = inflater.inflate(R.layout.a3,null);
        View a4 = inflater.inflate(R.layout.a4,null);
        View a5 = inflater.inflate(R.layout.a5,null);
        List<View> list=new ArrayList<>();
        list.add(a1);
        list.add(a2);
        list.add(a3);
        list.add(a4);
        list.add(a5);
        MyAdapter myAdapter=new MyAdapter(list);
        viewPager.setAdapter(myAdapter);


    }
}

/**
 * 自定义viewpager适配器
 */
class MyAdapter extends PagerAdapter{
    List<View> list;

    public MyAdapter(List<View> list) {
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view==object;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView(list.get(position));
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        container.addView(list.get(position));
        return list.get(position);
    }
}
